//
//  ProjectMainViewController.swift
//  XMGG
//
//  Created by iDev on 6/25/17.
//  Copyright © 2017 iDev. All rights reserved.
//

import UIKit
import SVProgressHUD
import Alamofire
import SwiftyJSON

class MainProjectViewController: UIViewController, UITableViewDelegate, MainProjectViewDelegate {

    var projectView:MainProjectView?
    override func viewDidLoad() {
        super.viewDidLoad()
        tabBarItem.title = "项目"
        let silderBtn = UIBarButtonItem(image: UIImage(named:"nav_btnsidebar"), style: .plain, target: self, action: nil)
        let addBtn = UIBarButtonItem(image: UIImage(named:"nav_btnadd"), style: .plain, target: self, action: #selector(addProject))
        let searchBtn = UIBarButtonItem(image: UIImage(named:"nav_btnsearch"), style: .plain, target: self, action: #selector(searchProject))
        navigationItem.leftBarButtonItem = silderBtn
        navigationItem.rightBarButtonItems = [addBtn,searchBtn]

        projectView = MainProjectView(frame: UIScreen.main.bounds)
        projectView?.delegate = self
        view.addSubview(projectView!)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        SVProgressHUD.show(withStatus: "获取项目中")
        setModles()
    }
    
    func mainProjectViewDidSelectRow(indexPath: IndexPath) {
        SVProgressHUD.show(withStatus: "获取中");
        let id = projectView!.modles![indexPath.row].PJId
        let param = ["tp_id":id]
        Alamofire.request(APIURL+"api/projects/content/info", method: .get, parameters: param, encoding: JSONEncoding.default, headers: nil).response { (response) in
            print(response)
            let modifyPJVC = ModifyProjectViewController()
            //        modifyPJVC.modle = getModifyModle(index: indexPath.row)
            modifyPJVC.mode = .view
            modifyPJVC.title = "项目详情"
            modifyPJVC.hidesBottomBarWhenPushed = true
            
            self.navigationController?.pushViewController(modifyPJVC, animated: true)
        }
    }
    
    func searchProject(){
        UserDefaults.standard.set(false, forKey: kNSDefaultIsLogin)
        UserDefaults.standard.set(nil, forKey: kNSDefaultPwd)
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "exitLogin"), object: nil)
    }
    
    func addProject(){
        let modifyPJVC = ModifyProjectViewController()
        modifyPJVC.title = "新建项目"
        modifyPJVC.hidesBottomBarWhenPushed = true
        modifyPJVC.modle = getTemplateModle(projectID: 0)
        modifyPJVC.mode = .add
        navigationController?.pushViewController(modifyPJVC, animated: true)
    }
    
    func setModles() {
        Alamofire.request(APIURL+"api/projects/info").response { (response) in
            guard let data = HasCommonNetWorkError(response: response) else{
                self.getError()
                return
            }
            self.handleData(data: data)
        }
    }
    
    func handleData(data:Data){
        let json = JSON(data)
        print(json)
        guard let code = json["code"].int , let result = json["result"].dictionary else{
            getError()
            return
        }
        
        guard let projects = result["projects_collection"]!.array else{
            getError()
            return
        }
        
        if code == 0 {
            getSuccess(projects: projects)
        }else{
            getError()
        }

    }
    
    func getSuccess(projects:[JSON]){
        var modles:[MainProjectModle] = []
        for project in projects{
            let modle = MainProjectModle(PJName: project["tp_name"].string!, PJMembers: ["成员"], PJTime: project["created_at"].string!, PJState: 1, PJId: project["id"].int!)
            modles.append(modle)
        }
        projectView?.modles = modles
        projectView?.reloadData()
        SVProgressHUD.dismiss()
    }
    
    func getError(){
        SVProgressHUD.dismiss()
        let alert = UIAlertController(title: nil, message: "获取项目失败", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "重试", style: .default, handler: { (action) in
//            self.setModles()
        }))
        self.present(alert, animated: true, completion: nil)
    }
    
//    func getModifyModle(index:Int)->ModifyProjectModle{
////        let (id, name) = testProjectID[index]
//        let id = projectView!.modles![index].PJId
//
//        let modle = ModifyProjectModle(projectID: id, projectTime: "132", projectName: (name,true), projectDetail: testDetailModle[index])
//        return modle
//    }

    func getTemplateModle(projectID:Int)->ModifyProjectModle{
        let time = ""
        let modle = ModifyProjectModle(projectID: projectID, projectTime: time, projectName: ("输入项目名称", true), projectDetail: testTemplateModle)
        return modle
    }
    
}

